package com.ocean.proxy.api.service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.ocean.core.common.system.SystemContext;
import com.ocean.core.common.threadpool.Parameter;
import com.ocean.persist.api.proxy.AdPullException;
import com.ocean.persist.api.proxy.JoinDSPEmu;
import com.ocean.persist.api.proxy.youdao.YoudaoAdPullParams;
import com.ocean.persist.api.proxy.youdao.YoudaoAdPuller;
import com.ocean.persist.api.proxy.youdao.YoudaoAdResponse;
import com.ocean.persist.common.ProxyConstants;
import com.ocean.persist.model.proxy.DSPPosition;
import com.ocean.proxy.api.base.AbstractAdSupplier;
import com.ocean.proxy.api.helper.InvenoIdGenerator;
import com.ocean.proxy.thrift.entity.AdContent;
import com.ocean.proxy.thrift.entity.AdImg;
import com.ocean.proxy.thrift.entity.AdMutiAction;
import com.ocean.proxy.thrift.entity.AdRecomReply;
import com.ocean.proxy.thrift.entity.AdRecomReq;
import com.ocean.proxy.thrift.entity.AdUserInfo;
import com.ocean.core.common.threadpool.workthread.AsynAbstractTask;
@Component(value="youdaoAdSupplier")
public class YoudaoAdSupplier extends AbstractAdSupplier{
    @Autowired 
	private YoudaoAdPuller youdaoAdPuller;
	private static final Map<String, Integer> netMap = new HashMap<String, Integer>();
	static{
	
		netMap.put(NETWORK_3G, 12);
		netMap.put(NETWORK_4G, 13);
	}
	
	public AdRecomReply invoke(InvokeAttribute attribute) throws AdPullException {
		
		AdRecomReq adreq = attribute.getAdreq();
		DSPPosition positionInfo = attribute.getDspPosition();
		// 参数转换
		YoudaoAdPullParams params = parseParams(adreq, positionInfo);
		// 调用API
		YoudaoAdResponse response = (YoudaoAdResponse) youdaoAdPuller.api(params,adreq.getHash(),String.valueOf(adreq.getUserAdSpaceAttri().getAdSpaceId()));
		// 解析结果
		return parseResult(response);
	}
	
	private AdRecomReply parseResult(YoudaoAdResponse response)
			throws AdPullException {
		
		if(response == null){
			return null;
		}
		
		// 返回对象
		AdRecomReply recomReply = new AdRecomReply();
		recomReply.setStatus(status);
		
		AdContent content = new AdContent();
		AdMutiAction action = new AdMutiAction();
		Integer atype = response.getYdAdType();
		// 广告类型，0：落地页广告；1：下载类型广告
		if(atype == 1){
			action.setType(ACTION_APP);
		}else{
			action.setType(ACTION_WEB);
		}
		String title = response.getTitle();
		if(StringUtils.isEmpty(title)){
			title = defTitle;
		}
		content.setMarketTitle(title);
		content.setGuideTitle(title);
		action.setGuideTitle(title);
		
		List<AdImg> imgs = new ArrayList<AdImg>();
		String image = response.getMainimage();
		if(StringUtils.isNotEmpty(image)){
			AdImg img = new AdImg();
			img.setSrc(image);
			imgs.add(img);
		}
		
		String icon = response.getIconimage();
		if(StringUtils.isNotEmpty(icon)){
			
			action.setCpIcon(icon);
			content.setCpIcon(icon);
			if(imgs.isEmpty()){
				AdImg img = new AdImg();
				img.setSrc(icon);
				imgs.add(img);
			}
		}
		// 图片地址
		content.setImglist(imgs);
		action.setLinkurl(response.getClk());
		
		content.setMutiAction(Collections.singletonList(action));
		//content.setAdId(InvenoIdGenerator.genThirdDspId(SystemContext.getDynamicPropertyHandler().getInt(ProxyConstants.PROXY_SERVER_NODE_INDEX,100)));

		
		Map<String, List<String>> map = new HashMap<String, List<String>>();
		// 点击监测
		List<String> click = response.getClktrackers();
		if(click == null){
			click = new ArrayList<String>();
		}
		map.put(CLICK, click);
		// 曝光监测
		List<String> show = response.getImptracker();
		if(show == null){
			show = new ArrayList<String>();
		}
		map.put(SHOW, show);
		
		content.setThirdReportLinks(map);
		recomReply.setAd_content(content);
		
		return recomReply;
	}
	
	private YoudaoAdPullParams parseParams(AdRecomReq adreq, 
			DSPPosition positionInfo) throws AdPullException {
		
		AdUserInfo userInfo = adreq.getUserinfo();
		
		YoudaoAdPullParams params = new YoudaoAdPullParams();
		params.setId(positionInfo.getPos());
		String adid = userInfo.getAdid();


		
		String net = adreq.getNet();
		Integer dct = netMap.get(net);
		if(dct != null){
			// 子网络连接类型。当ct字段为MOBILE时添加，为3G时值为12，4G时为13
			params.setDct(dct);
			// 网络连接类型，（ UNKNOWN, ETHERNET,
			// WIFI, MOBILE;），值可能为0,1,2,3，分别以上几种广告连接状态
			params.setCt(3);
		}
		else if(NETWORK_WIFI.equals(net)){
			params.setCt(2);
		
		}else{
			params.setCt(0);
		}
		if(StringUtils.isNotEmpty(adid)){
			params.setAuidmd5(DigestUtils.md5Hex(adid));
			params.setUdid(adid);
		}
		
		params.setImei(userInfo.getImei());
		params.setImeimd5(DigestUtils.md5Hex(userInfo.getImei()));
		params.setMcc("460");
		params.setIso("cn");
		params.setRip(userInfo.getClient_ip());
		params.setDn(encode(userInfo.getPhonemodel()));
		String mobile = userInfo.getMobile();
		if(MOBILE_CMCC.equals(mobile)){
			params.setMnc("00");
			params.setCn("中国移动");
		} else if(MOBILE_CUCC.equals(mobile)){
			params.setMnc("01");
			params.setCn("中国联通");
		}else if(MOBILE_CTCC.equals(mobile)){
			params.setMnc("03");
			params.setCn("中国电信");
		}
		params.setRip(userInfo.getClient_ip());
		return params;
	}

	public YoudaoAdPuller getYoudaoAdPuller() {
		return youdaoAdPuller;
	}

	public void setYoudaoAdPuller(YoudaoAdPuller youdaoAdPuller) {
		this.youdaoAdPuller = youdaoAdPuller;
	}

}
